import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
import { db } from "@/db";
import { eq } from "drizzle-orm";
import { users } from "@/db/schema";
import { DrizzleAdapter } from "@auth/drizzle-adapter";
// 验证用户名和密码
async function getUserByUsernameAndPassword(credentials: { username: string; password: string }) {
	if (!credentials.username || !credentials.password) {
		return null;
	}

	// 从数据库查询用户
	const user = await db.select().from(users).where(eq(users.username, credentials.username)).limit(1);
	// 验证用户是否存在及密码是否匹配
	// 注意：实际生产环境中应使用bcrypt等工具进行密码哈希比较

	if (user.length == 0 || !user || user[0].password !== credentials.password) {
		return null;
	}

	return user;
}

export const { handlers, signIn, signOut, auth } = NextAuth({
	adapter: DrizzleAdapter(db),
	providers: [
		Credentials({
			credentials: {
				username: { label: "用户名", type: "text" },
				password: { label: "密码", type: "password" },
			},
			authorize: async (credentials) => {
				if (!credentials) return null;

				const { username, password } = credentials;
				const dbUser = await getUserByUsernameAndPassword({ username: username as string, password: password as string });
				if (!dbUser) {
					throw new Error("用户不存在或密码错误");
				}

				return {
					id: dbUser[0].id,
					email: dbUser[0].email,
					username: dbUser[0].username
				};
			},
		}),
	],
	callbacks: {
		jwt({ token, user }) {
			if (user) {
				token.id = user.id;
				token.username = user.name;
			}
			return token;
		},
		session({ session, token }) {
			if (session.user) {
				session.user.id = token.id as string;
				// @ts-ignore
				session.user.username = token.username as string;
			}
			return session;
		},
	},
	session: {
    strategy: "jwt",
  },
  pages: {
    signIn: "/sign-in",
  },
  secret: process.env.AUTH_SECRET,
  debug: process.env.NODE_ENV === "development",
});